package uk.ac.cam.tcs40.sidnet;

import uk.ac.cam.tcs40.sidnet.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class LoginActivity extends Activity {

	private TextView m_Status;
	private EditText m_Username, m_Password;
	private StringBuilder m_Error;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		m_Status = (TextView) findViewById(R.id.status);

		m_Username = (EditText) findViewById(R.id.username);
		m_Password = (EditText) findViewById(R.id.password);

		final Button loginButton = (Button) findViewById(R.id.submit);
		loginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new LoginTask().execute();
			}
		});
	}

	private void showStatus(final String status, boolean error) {
		m_Status.setVisibility(View.INVISIBLE);
		
		if (error)
			m_Status.setTextColor(Color.RED);
		else
			m_Status.setTextColor(Color.BLACK);

		m_Status.setText(status);
		m_Status.setVisibility(View.VISIBLE);
	}

	private void showSpinner(final boolean show) {
		ProgressBar loading = (ProgressBar)findViewById(R.id.loading);
		if (show)
			loading.setVisibility(View.VISIBLE);
		else
			loading.setVisibility(View.GONE);
	}

	private void clearPassword() {
		m_Password.setText(null);
	}

	private class LoginTask extends AsyncTask<Void, Void, Boolean> {
		protected void onPreExecute() {
			showStatus("Logging in", false);
			showSpinner(true);
		}

		protected Boolean doInBackground(Void... v) {
			m_Error = new StringBuilder();
			return Hall.getInstance().login(m_Username.getText().toString(), m_Password.getText().toString(), m_Error);
		}

		protected void onProgressUpdate(Void... progress) {
		}

		protected void onPostExecute(Boolean result) {
			if (result) {
				Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				LoginActivity.this.startActivity(intent);

				finish();

			} else {
				showSpinner(false);
				showStatus(m_Error.toString(), true);
				clearPassword();
			}
		}
	}
}
